package fi.laurea.examples.base64;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class BufferImageBase64Coder {

	public static String encode(BufferedImage image) throws IOException {
		String base64 = null;
		
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ImageIO.write(image, "jpg", baos);
		baos.flush();
		byte[] imageInByte = baos.toByteArray();
		baos.close();
		base64 = new String(Base64Coder.encode(imageInByte));

		return base64;
	}

	public static BufferedImage decode(String base64) throws IOException {
		BufferedImage img = null;
		byte[] imageInByte = Base64Coder.decode(base64);
		InputStream in = new ByteArrayInputStream(imageInByte);
		img = ImageIO.read(in);
		return img;
	}

	public static void main(String[] args) {
		BufferedImage img = null;
		try {
			img = ImageIO.read(new File("media/test.jpg"));
		
			String imageAsText = BufferImageBase64Coder.encode(img);
			System.out.println("<img src=\"data:image/gif;base64,"+imageAsText+"\"/>");

			img =  BufferImageBase64Coder.decode(imageAsText);
			JFrame frame = new JFrame();
			frame.add(new JLabel(new ImageIcon( img )));
			frame.setVisible(true);

			
			
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
